package com.codebuffer.nowcoder;

import java.util.Iterator;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingDeque;

public class MovingCount {

    public static int movingCount(int threshold, int rows, int cols) {
        if(threshold==0&&rows==0&& cols==0){
            return 0;
        }
        Queue<String> queue = new LinkedBlockingDeque<>(rows*cols);
        int count = 0;
        int arr[][] = new int[rows][cols];

        queue.add("0,0");
        arr[0][0] = -1;
        String poll = null;
        while ((poll=queue.poll())!=null){
            String[] split = poll.split(",");
            Integer r = Integer.parseInt(split[0]);
            Integer c = Integer.parseInt(split[1]);
            count++;
            addChild(r,c,arr,threshold,queue);
        }
        return count;
    }

    private static void addChild(int r, int c, int[][] arr,int threshold,Queue<String> queue) {
        System.out.println(r+","+c);
        if(r+1<arr.length && arr[r+1][c]!=-1 && sum(r+1,c)<=threshold ){
            queue.add(""+(r+1)+","+c);
            arr[r+1][c] = -1;
        }
        if(r-1>=0 && arr[r-1][c]!=-1 && sum(r-1,+c)<=threshold ){
            queue.add(""+(r-1)+","+c);
            arr[r-1][c] = -1;
        }
        if(c+1<arr[r].length && arr[r][c+1]!=-1 && sum(r,c+1)<=threshold ){
            queue.add(""+r+","+(c+1));
            arr[r][c+1] = -1;
        }
        if(c-1>=0 && arr[r][c-1]!=-1 && sum(r,c-1)<=threshold ){
            queue.add(""+r+","+(c-1));
            arr[r][c-1] = -1;
        }

    }


    private static int sum(int x,int y) {
        int sum = 0;
        while(y>0){
            sum += y%10;
            y=y/10;
        }
        while(x>0){
            sum += x%10;
            x=x/10;
        }
        return sum;
    }

    public static void main(String[] args) {
        System.out.println(movingCount(15,20,20));
    }
}
